#!/bin/bash

# this project absolute path
PRJ_PATH=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)

# binaries build prefix install path
PRFX_PATH=$PRJ_PATH/install

# binaries finally install path if needed
#INST_PATH=/tftp

# config file path
CONF_FILE=$PRJ_PATH/config.json

# shell script will exit once get command error
set -e

#+-------------------------+
#| Shell script functions  |
#+-------------------------+

function pr_error() {
    echo -e "\033[40;31m $1 \033[0m"
}

function pr_warn() {
    echo -e "\033[40;33m $1 \033[0m"
}

function pr_info() {
    echo -e "\033[40;32m $1 \033[0m"
}

# decompress a packet to destination path
function do_unpack()
{
    tarball=$1
    dstpath=`pwd`

    if [[ $# == 2 ]] ; then
        dstpath=$2
    fi

    pr_info "decompress $tarball => $dstpath"

    mkdir -p $dstpath
    case $tarball in
        *.tar.gz)
            tar -xzf $tarball -C $dstpath
            ;;

        *.tar.bz2)
            tar -xjf $tarball -C $dstpath
            ;;

        *.tar.xz)
            tar -xJf $tarball -C $dstpath
            ;;

        *.tar.zst)
            tar -I zstd -xf $tarball -C $dstpath
            ;;

        *.tar)
            tar -xf $tarball -C $dstpath
            ;;

        *.zip)
            unzip -qo $tarball -d $dstpath
            ;;

        *)
            pr_error "decompress Unsupport packet: $tarball"
            return 1;
            ;;
    esac
}

# parser configure file and export environment variable
function do_export()
{
    export BOARD=`jq -r ".bsp.board" $CONF_FILE | tr 'A-Z' 'a-z'`
    export VARIANT=`jq -r ".bsp.variant" $CONF_FILE | tr 'A-Z' 'a-z'`
    export SDKVER=`jq -r ".bsp.sdkver" $CONF_FILE | tr 'A-Z' 'a-z'`
    export TARBALL=`jq -r ".bsp.tarball" $CONF_FILE`
    export BDPATH=`jq -r ".bsp.build" $CONF_FILE`
    export WKSP=$BDPATH/$BOARD/$SDKVER
}

function do_fetch()
{
    cd $PRJ_PATH && mkdir -p $WKSP

    if [ -f $WKSP/u-boot/Makefile ] ; then
        pr_info "SDK $SDKVER source code fetched already"
        if [ ! -e $PRJ_PATH/$SDKVER ] ; then
            ln -sf $WKSP $PRJ_PATH/$SDKVER
        fi
        return 0;
    fi

    pr_info "start fetch $SDKVER source code"

    if [ ! -d $WKSP/.repo ] ; then
        # decompress source code packet
        do_unpack $TARBALL $WKSP
    fi

    if [ ! -s $SDKVER ] ; then
        ln -sf $WKSP $SDKVER
    fi

    cd $PRJ_PATH/$SDKVER && pwd

    if [ ! -e $WKSP/u-boot/Makefile ] ; then
        pr_info "repo sync source code ...."
        .repo/repo/repo sync -l
    fi
}

function do_patch()
{
    PATCHES_PATH=$PRJ_PATH/patch

    cd $PRJ_PATH/$SDKVER && pwd

    # decompress source
    for f in $PATCHES_PATH/package/*.tar.*
    do
        tar_dir=$(basename $f | sed 's/\..*$//' | sed 's/-/\//g')
        if [ ! -d $tar_dir ]  ;then
            do_unpack $f $(dirname $tar_dir)
        fi
    done

    # do patches
    for f in $PATCHES_PATH/*.patch
    do
        patch_name=$(basename $f)
        patch_path=$(echo "$patch_name" | sed 's/_/\//g; s/\.patch$//')
        if [ ! -f $patch_path/patched.tag ] ; then
            pr_warn "do patch for $patch_path now..."
            cd $patch_path && patch -p1 < $f && cd -
        else
            pr_warn "$patch_path patched already."
        fi
    done
}

function do_config()
{
    pr_warn "start menuconfig $SDKVER"

    cd $PRJ_PATH/$SDKVER && pwd

    # kernel -> kernel/arch/arm64/configs/rockchip_linux_defconfig
    ./build.sh kconfig

    # buildroot -> buildroot/configs/rockchip_rk3568_defconfig
    ./build.sh bconfig
}

function do_build()
{
    PRODUCT=rk3568_t

    cd $PRJ_PATH/$SDKVER && pwd

    pr_warn "start build $SDKVER"

    pr_info "initial envsetup"
    source build/envsetup.sh

    # lunch <product_name>-<build_variant(user|userdebug|eng)>
    lunch ${PRODUCT}-${VARIANT}
    #        eng(Engineering Build) -- Target Users: Developers
    #       user(User Build)        -- Target Users: Testers
    #  userdebug(User Debug Build)  -- Target Users: End consumers

    pr_info "start build $DISTRO sdk"

    # -A = build android
    # -U = build uboot
    # -C = build kernel with Clang
    # -K = build kernel
    # -u = build update.img
    ./build.sh -AUCKu
    # -p = will build packaging in IMAGE
    # -o = build OTA package
    # -v = build android with 'user' or 'userdebug'
    # -d = huild kernel dts name    "
    # -J = build jobs    "


    echo ""

    pr_warn "output images path: $PRJ_PATH/$SDKVER/rockdev/Image-${PRODUCT}"
    ls $PRJ_PATH/$SDKVER/rockdev/Image-${PRODUCT}
    echo ""
}

function do_clean()
{
    cd $PRJ_PATH/$SDKVER && pwd

    ./build.sh cleanall
}

#+-------------------------+
#| Shell script body entry |
#+-------------------------+

do_export

if [[ $# == 1 && $1 == -c ]] ;then
    pr_warn "start clean $SDKVER"
    do_clean
    exit;
fi

pr_warn "start build $SDKVER for ${BOARD}"

do_fetch

do_patch

exit;

do_build

